package com.windgo.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.windgo.util.StringUtil;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author stone
 * @date 2022/09/07 10:54
 */

// 当数据库中的列和引用类型中的成员变量是对应的类型的时候，会自动使用TypeHandler
@MappedTypes(Integer[].class)//java类型
@MappedJdbcTypes(JdbcType.VARCHAR)//数据库类型
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {
    ObjectMapper objectMapper = new ObjectMapper();
    //private static final  String splitCharset=",";


    //输入映射
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(integers);//也可以用Gson
        preparedStatement.setString(i,value);
    }

    //输出映射
    @Override
    public Integer[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String result = resultSet.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String result = callableStatement.getString(columnIndex);
        return transfer(result);
    }

    @SneakyThrows
    private Integer[] transfer(String result) {
        //可以使用JSON工具类来做转化
        if (!StringUtil.isEmpty(result)){
            Integer[] integers = objectMapper.readValue(result,Integer[].class);
            return integers;
        }
        return new Integer[0];
    }

    // private static String arrayToString(Integer[] array){
    //     StringBuilder stringBuilder = new StringBuilder();
    //     if (array != null && array.length >0){
    //         for (Integer integer : array) {
    //             stringBuilder.append(splitCharset).append(integer.toString());
    //         }
    //         stringBuilder.append(splitCharset);
    //     }
    //     return stringBuilder.length() > 0 ? stringBuilder.toString() : null;
    // }


}
